#!/bin/bash

NAMESPACE="kubesphere-system"
REGISTRY_PREFIX="reg.sumztech.com:100"

# 三个需要处理的 Deployment
DEPLOYMENTS=("ks-apiserver" "ks-controller-manager" "ks-console")

for dep in "${DEPLOYMENTS[@]}"; do
  # 检查 Deployment 对应的 Pod 是否存在 ImagePullBackOff 状态
  if ! /usr/local/bin/kubectl -n "$NAMESPACE" get pod -l "app=$dep" -o jsonpath="{.items[*].status.containerStatuses[?(@.state.waiting.reason=='ImagePullBackOff')]}" | grep -q "ImagePullBackOff"; then
    /usr/bin/echo "[$dep] 未检测到 ImagePullBackOff 状态，跳过"
    continue
  fi

  # 获取当前镜像
  CURRENT_IMAGE=$(/usr/local/bin/kubectl -n "$NAMESPACE" get deploy "$dep" -o jsonpath="{.spec.template.spec.containers[0].image}")

  # 判断是否已经加了前缀
  if [[ "$CURRENT_IMAGE" == "$REGISTRY_PREFIX"* ]]; then
    /usr/bin/echo "[$dep] 镜像已经是 $CURRENT_IMAGE，跳过"
    continue
  fi

  # 拼接新镜像
  NEW_IMAGE="$REGISTRY_PREFIX/$CURRENT_IMAGE"
  /usr/bin/echo "[$dep] 检测到 ImagePullBackOff，更新镜像: $CURRENT_IMAGE -> $NEW_IMAGE"

  # 更新 Deployment 镜像
  /usr/local/bin/kubectl -n "$NAMESPACE" set image "deployment/$dep" "$dep=$NEW_IMAGE"
done